'use strict';
define(['jquery','angular','uiBootstrap'],function($,angular){
	angular.module('app.attachments', ['ui.bootstrap'])	
	.directive('attachments',['$rootScope', '$http', 'Upload', '$modal', 'OssEndpoint'
		, function($rootScope, $http, Upload, $modal, OssEndpoint){
		 
		 return {
			  require: '?ngModel',
			  restrict: 'EA', // E = Element, A = Attribute, C = Class, M = Comment
//				  template: '<div>hello template</div>',
			  templateUrl: function(element, attrs) {
			      return attrs.templateUrl || 'js/_directives/attachments.html';
			  },
			  replace: false,
			  scope: {
				  data: '=',        
				  permission: "@",//公司还是个人:private:个人，public:公司    
				  cantedit: "&",            
				  width: "@",            
				  height: "@", 
				  cols: "@cols",//列数
				  count: "@count", //可以上传的总数量
			  },
			  controller:['$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude){
//					  console.log('$scope-->',$scope);
//					  console.log('$element-->',$element);
//					  console.log('$attrs-->',$attrs);
//					  console.log('$transclude-->',$transclude);
				  //图片存放的服务器
				  $scope.imgServerUrl = OssEndpoint.imgEndpointUrl;
				  
				  $scope.colsInit = function(){
					  if($scope.cols==undefined){
//							  console.log('$scope.cols-->',$scope.cols);
						  //默认是显示6列（总宽度是12列）
						  $scope.col = 2;
					  }else{
						  $scope.col = 12 / $scope.cols;
					  }
//						  console.log('$scope.col-->',$scope.col);
				  }
				  
				  //自定义图片尺寸
				  $scope.optionStyle = {
						  width:$scope.width
						  ,height:$scope.height
						  
				  };
				  
				  //初始化上传总数量
				  if($scope.count==undefined){
//						  console.log('$scope.cols-->',$scope.cols);
					  //表示不限制上传数量
					  $scope.count = 0;
				  }
				  
				  $scope.dataFiles = null;


			 }],
			 link:function (scope, element, attrs, ngModel){
//					 console.log('scope.relativePath-->',scope.relativePath);
//					 console.log('scope.cantedit-->',scope.cantedit);
//					 console.log('scope.acceptType-->',scope.acceptType);
				 //初始化
				 //下面这个不起作用，无法按赋值路径进行上传
//					  if(scope.relativePath==undefined || scope.relativePath==''){
//						  console.log('scope.relativePath-->',scope.relativePath);
//						  scope.relativePath = '/attachments';
//						  console.log('scope.relativePath-->',scope.relativePath);
//					  }
//					 console.log('scope.dataFiles-->',scope.dataFiles);
//					 if(ngModel.$viewValue==null){
//					 if(isNaN(ngModel.$viewValue)){
//						 scope.dataFiles = [];
//					 }else{
//						 scope.dataFiles = angular.fromJson(ngModel.$viewValue);
//					 }
				 
				 //渲染完成之后才能得到ngModel真正的值
				ngModel.$render = function() {
//					console.log('ngModel.$viewValue-->',ngModel.$viewValue);
//					console.log('scope.dataFiles-->',scope.dataFiles);
					if(ngModel.$viewValue==null){
//						if(isNaN(ngModel.$viewValue)){
						scope.dataFiles = null;
					}else{
						scope.dataFiles = angular.fromJson(ngModel.$viewValue);
//						scope.dataFiles = ngModel.$viewValue;
					}
//					console.log('scope.dataFiles-->',scope.dataFiles);
				};

		            
//					 console.log('scope.dataFiles-->',scope.dataFiles);
				
//					    scope.filesChanged = function ($files, $file, $newFiles, $duplicateFiles, $invalidFiles,$event) {
				scope.filesChanged = function ($files, $file) {
//						    	console.log('filesChanged.$files-->',$files);
//						    	console.log('filesChanged.$file-->',$file);
//						    	console.log('filesChanged.$newFiles-->',$newFiles);
//						    	console.log('filesChanged.$duplicateFiles-->',$duplicateFiles);
//						    	console.log('filesChanged.$invalidFiles-->',$invalidFiles);
//						    	console.log('filesChanged.$event-->',$event);
			    	if($file){
			    		scope.upload($file);
			    	}
			    };

			    // upload on file select or drop
			    
			    scope.upload = function (file) {
//					    console.log('file-->',file);
			    	var url = '';
			    	if(scope.permission=='public'){
			    		//公司文档
			    		url = $rootScope.getProjectName() + '/baseinfo/fastdfsFiles/list/upload';
			    	}
				    if(scope.permission=='private'){
			    		//个人文档
			    		url = $rootScope.getProjectName() + '/backcenter/fastdfsFiles/list/upload';
			    	}
			    	
			        Upload.upload(
			        		{
					            url: url,
					            data: {file: file, 'lastModified': file.lastModified, 'fileScale': file.$ngfWidth+'X'+file.$ngfHeight,'destDir':'/'}
			        		}
			        ).then(function (resp) {
			        	//console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' , resp.data);
			        	if(resp.data.code==0){
			        		//上传成功
				        	if(scope.dataFiles == null){
				        		scope.dataFiles = [];
				        	}
				        	
				        	scope.dataFiles.push(resp.data.data);
				        	
				        	//去掉scope.dataFiles中的$$hashKey（以后处理）
				        	var imagesData = [];
				        	if(scope.dataFiles.length>0){
					        	for(var i=0;i<scope.dataFiles.length;i++){
//							        		delete scope.dataFiles[i]["$$hashKey"];
					        		/*
						        	var obj = {
						        			"docID":scope.dataFiles[i].docID
						        			,"docSuffix":scope.dataFiles[i].docSuffix
						        			,"docName":scope.dataFiles[i].docName
						        			,"docPath":scope.dataFiles[i].docPath
						        			,"size":scope.dataFiles[i].size
						        			,"time":scope.dataFiles[i].time
						        	}
					        		*/
						        	var obj = {
						        			"groupName":scope.dataFiles[i].groupName
						        			,"remoteFileName":scope.dataFiles[i].remoteFileName
						        			,"originalFilename":scope.dataFiles[i].originalFilename
						        	}
						        	
						        	imagesData.push(obj);
					        	}
				        	}else{
				        		imagesData = scope.dataFiles;
				        	}
//					        		console.log('imagesData-->',imagesData);
			        		
				            ngModel.$setViewValue(imagesData);
//						            console.log('scope.dataFiles-->',scope.dataFiles);
//									console.log('ngModel.$viewValue-->',ngModel.$viewValue);
			        		
			        	}else{
			        		//上传失败
			        		alert('文件上传失败！');
			        	}
			            
			        }, function (resp) {
//						            console.log('Error status: ' + resp.status);
			        }, function (evt) {
			            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//						            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
			            file.progress = progressPercentage;
//						            console.log('scope.files',scope.files);
			        });
			    };
			    
			    scope.remove = function(file){
			    	var index = scope.dataFiles.indexOf(file);
//					    	console.log('index-->',index);
			    	scope.dataFiles.splice(index,1);
			    	if(scope.dataFiles.length==0){
			    		ngModel.$setViewValue(null);
			    	}else{
			        	//去掉scope.dataFiles中的$$hashKey（以后处理）
			    		ngModel.$setViewValue(scope.dataFiles);
			    	}
			    };
				
				//打开对话框（选择图片）
			  scope.triggerImagesClick = function(){
				  
					var options = {};
					options.recordState = 'none';
					options.permission = scope.permission;
					
					var title = '图库';

					var modalInstance = $modal.open({  
			        	backdrop: 'static',
			        	size: 'lg',
			            templateUrl: 'js/_directives/attachimages-select.html',  
			            controller: 'fileListSelectSingleCtrl as Model',  
			            resolve: {
			                params: function () {  
			                    return angular.copy(options);  
			                }
		                    ,title : function() { return title; }
				        }
			        });  
					
			        //模态窗口关闭之后执行的事件
			        modalInstance.result.then(function (event) {  
			             //成功关闭窗口
			         	var returnData = event.data;
			         	//debugger;
			             try {
			             	for ( var i = 0; i < returnData.length; i++) {
			             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);

			             		if(scope.dataFiles == null){
					        		scope.dataFiles = [];
					        	}
					        	/*
					        	var o = {
					        			"docID":returnData[i].fID
					        			,"docSuffix":returnData[i].fileSuffix
					        			,"docName":returnData[i].originalFilename
					        			,"docPath":returnData[i].relativePath
					        			,"size":returnData[i].fileSize
					        			,"time":returnData[i].lastModified
					        	}
					        	*/
					        	var o = {
					        			"groupName":returnData[i].groupName
					        			,"remoteFileName":returnData[i].remoteFileName
					        			,"originalFilename":returnData[i].originalFilename
					        	}
					        	
					        	scope.dataFiles.push(o);
					        	
					        	//去掉scope.dataFiles中的$$hashKey（以后处理）
					        	var imagesData = [];
					        	if(scope.dataFiles.length>0){
						        	for(var i=0;i<scope.dataFiles.length;i++){
//								        		delete scope.dataFiles[i]["$$hashKey"];
						        		/*
							        	var obj = {
							        			"docID":scope.dataFiles[i].docID
							        			,"docSuffix":scope.dataFiles[i].docSuffix
							        			,"docName":scope.dataFiles[i].docName
							        			,"docPath":scope.dataFiles[i].docPath
							        			,"size":scope.dataFiles[i].size
							        			,"time":scope.dataFiles[i].time
							        	}
							        	*/
						        		
							        	var obj = {
							        			"groupName":scope.dataFiles[i].groupName
							        			,"remoteFileName":scope.dataFiles[i].remoteFileName
							        			,"originalFilename":scope.dataFiles[i].originalFilename
							        	}
							        	
							        	imagesData.push(obj);
						        	}
					        	}else{
					        		imagesData = scope.dataFiles;
					        	}
//						        		console.log('imagesData-->',imagesData);

				        		ngModel.$setViewValue(imagesData);
			         			
			                 }
			             } finally {
			             	return;
			             }

			        }, function (reason) {  
			            console.info('Modal dismissed at: ' + new Date());  
			        });  
					
				};

			 
			 }
			 
		 };
	 }])
	 .controller('fileListSelectSingleCtrl'
				,['$rootScope', '$scope', 'BizData', '$modalInstance','params', 'title','OssEndpoint'
				   , function ($rootScope, $scope, BizData, $modalInstance, params, title, OssEndpoint) {
						
					var Model = this;
					
					//图片存放的服务器
					$scope.imgServerUrl = OssEndpoint.imgEndpointUrl;
					
					Model.dataFileListIndexChanged = function(event) {
					
					}

					//////////////////////对话框使用开始//////////////////////////////////////
					
			        //模态窗口打开之后执行的事件
			        $modalInstance.opened.then(function(){
			    		//接收调用对话框的参数
			        	Model.title = title;  
			        	Model.params = params; 
			        	console.log(params.permission);
			    		//设置过滤条件
			        	var reader = '';
			        	var filter = '';
			        	var defCols = '';
			        	var concept = '';
						if(params.permission=='public'){
							//公司文档
							concept = 'OrgFileList';
							defCols = {fID:{name:"fID",type:"String",label:""},originalFilename:{name:"originalFilename",type:"String",label:""},fileSuffix:{name:"fileSuffix",type:"String",label:""},fileSize:{name:"fileSize",type:"Decimal",label:""},lastModified:{name:"lastModified",type:"long",label:""},contentType:{name:"contentType",type:"String",label:""},fileScale:{name:"fileScale",type:"String",label:""},sDescription:{name:"sDescription",type:"String",label:""},groupName:{name:"groupName",type:"String",label:""},remoteFileName:{name:"remoteFileName",type:"String",label:""},cUsercode:{name:"cUsercode",type:"String",label:""},cUsername:{name:"cUsername",type:"String",label:""},cDatetime:{name:"cDatetime",type:"Datetime",label:""},userId:{name:"userId",type:"String",label:""},enterpriseNo:{name:"enterpriseNo",type:"String",label:""},enterpriseName:{name:"enterpriseName",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
							reader = '/baseinfo/fastdfsFiles/list/query'; 
							filter = "OrgFileList.contentType like '%image%'";
						}
						if(params.permission=='private'){
							//个人文档
							concept = 'PersonFileList';
							defCols = {fID:{name:"fID",type:"String",label:""},originalFilename:{name:"originalFilename",type:"String",label:""},fileSuffix:{name:"fileSuffix",type:"String",label:""},fileSize:{name:"fileSize",type:"Decimal",label:""},lastModified:{name:"lastModified",type:"long",label:""},contentType:{name:"contentType",type:"String",label:""},fileScale:{name:"fileScale",type:"String",label:""},sDescription:{name:"sDescription",type:"String",label:""},groupName:{name:"groupName",type:"String",label:""},remoteFileName:{name:"remoteFileName",type:"String",label:""},cUsercode:{name:"cUsercode",type:"String",label:""},cUsername:{name:"cUsername",type:"String",label:""},cDatetime:{name:"cDatetime",type:"Datetime",label:""},userId:{name:"userId",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
							reader = '/backcenter/fastdfsFiles/list/query'; 
							filter = "PersonFileList.contentType like '%image%'";
						}
						
						var options = {};
						options.container = Model;
						options.concept = concept;
						options.name = 'dataList';
						options.url = $rootScope.path;
						options.httpUrl = $rootScope.getServiceName();
						options.creater = '';
						options.reader = reader;
						options.writer = '';
						options.deleter = '';
						options.idColumnDefine = "fID";
						options.idColumnName = "fID";
						options.defCols = defCols;
						options.isTree = false;
						options.parentRelation = 'sParent';
						options.nodeKindRelation = 'sNodeKind';
						options.nodeLevelRelation = 'sLevel';
						options.pathRelation = 'sFID';
						options.directDeleteMode = true;
						options.limit = 12;
						
						options.onIndexChanged = Model.dataFileListIndexChanged;
						
						$scope.dataFileList = new BizData(options);
						$scope.dataFileList.filter = filter;

			    		//刷新数据
			    	    $scope.dataFileList.refreshData();
			        });  
					
			        Model.ok = function () {  
				    	//保存成功
				    	//打包数据
				    	var event = {};
				    	var data = [];
				    	var sourceRow = $scope.dataFileList.rows[$scope.dataFileList.currentIndex];
				    	var row = {};
						//循环行中的列，判断变化点是哪一个
						for(var obj in sourceRow){
							if(obj!='$$hashKey' && obj!='userdata'){
								row[obj] = sourceRow[obj].value;
							}
						}
				    	
				    	data.push(row);
				    	event.data = data;
						$modalInstance.close(event);  
				    };  
				    
				    Model.cancel = function () {  
				        $modalInstance.dismiss('cancel');  
				    };    
					//////////////////////对话框使用结束//////////////////////////////////////

				    return Model;
				    
				}	
		])//控制器结束
	 
});//define结束

